/*eslint-disable*/
import { ElMessage } from "element-plus";
import mainApi from "@/api/mainApi.js";
import courtIdDictionary from "../json/dictionary/courtIdDictionary";

const path = window.myApi.path;
const fs = window.myApi.fs;

export default {
    // 文件上传总起
    uploadFileRun(fileList, describeList, type) {
        mainApi.readJson(ElMessage, (data) => {
            let fileHouse = path.join(data.fileHouse, type);
            let pathList, targetPathList,modNameList;

            switch (type) {
                case "court":
                    modNameList = courtIdDictionary.filter(item => item.value === describeList[0].data).map(obj => obj.id);
                    pathList = this.confirmFinalNameAndPath(describeList, fileHouse, modNameList);
                    targetPathList = [
                        { name: "_fxxx.iff", filePath: pathList.modPathList[0] },
                        { name: "预览图.jpg", filePath: path.join(pathList.previewFolderPath, "preview.jpg") }
                    ];
                    break;
                case "jersey":
                    pathList = this.confirmFinalNameAndPath_Jersey(describeList, fileHouse, fileList);
                    targetPathList = fileList.map((file, index) => ({
                        name: file.name,
                        filePath: pathList.modPathList[index]
                    }));
                    break;
                case "face":
                    modNameList = [describeList[0].data.split("|")[0]];
                    pathList = this.confirmFinalNameAndPath_Face(describeList, fileHouse, modNameList);
                    targetPathList = [
                        { name: "_png.iff", filePath: path.join(pathList.faceFolderPath, `png${modNameList[0]}.iff`) },
                        { name: "_face.iff", filePath: path.join(pathList.faceFolderPath, `face${modNameList[0]}.iff`) },
                        { name: "预览图.jpg", filePath: path.join(pathList.previewFolderPath, "preview.jpg") }
                    ];
                    break;
                case "blacktop":
                    describeList.unshift({});
                    pathList = this.confirmFinalNameAndPath(describeList, fileHouse, ["s616"]);
                    targetPathList = [
                        { name: "s616.iff", filePath: pathList.modPathList[0] },
                        { name: "预览图.jpg", filePath: path.join(pathList.previewFolderPath, "preview.jpg") }
                    ];
                    break;
                case "scoreboard":
                    describeList.unshift({});
                    pathList = this.confirmFinalNameAndPath(describeList, fileHouse, ["newscorebug"]);
                    targetPathList = [
                        { name: "newscorebug.iff", filePath: pathList.modPathList[0] },
                        { name: "预览图.jpg", filePath: path.join(pathList.previewFolderPath, "preview.jpg") }
                    ];
                    break;
                default:
                    ElMessage.error({ message: `未知的文件类型: ${type}` });
                    return;
            }
            this.modFileStore(pathList, fileList, targetPathList);
        });
    },
    // 确认最终文件名及路径
    confirmFinalNameAndPath(describeList, fileHouse, modNameList) {
        let mainFolderName = `0 ${describeList[1].data + Math.floor(Date.now() / 1000)} ${describeList[2].data}`;
        let mainFolderPath = path.join(fileHouse, mainFolderName);
        let modPathList = modNameList.map(name => path.join(mainFolderPath, `${name}.iff`));
        let previewFolderPath = path.join(mainFolderPath, 'preview');

        return {
            modPathList,
            newFolderList: [mainFolderPath, previewFolderPath],
            mainFolderPath,
            previewFolderPath
        };
    },
    // 确认最终文件名及路径-面补
    confirmFinalNameAndPath_Face(describeList, fileHouse, modNameList) {
        let faceId = modNameList[0];
        let faceListFolderPath = path.join(fileHouse, faceId);
        let isNewPlayer = !fs.existsSync(faceListFolderPath);
        let faceFolderPath, previewFolderPath;

        if (isNewPlayer) {
            faceFolderPath = path.join(faceListFolderPath, `${faceId}-1 ${describeList[1].data} ${describeList[2].data}`);
            previewFolderPath = path.join(faceFolderPath, "preview");
            return {
                newFolderList: [faceListFolderPath, faceFolderPath, previewFolderPath],
                faceFolderPath,
                previewFolderPath
            };
        } else {
            let newFaceIndex = Math.max(...fs.readdirSync(faceListFolderPath).map(element => Number(element.split(" ")[0].split("-")[1]))) + 1;
            faceFolderPath = path.join(faceListFolderPath, `${faceId}-${newFaceIndex} ${describeList[1].data} ${describeList[2].data}`);
            previewFolderPath = path.join(faceFolderPath, "preview");
            return {
                newFolderList: [faceFolderPath, previewFolderPath],
                faceFolderPath,
                previewFolderPath
            };
        }
    },
    // 确认最终文件路径-球衣
    confirmFinalNameAndPath_Jersey(describeList, fileHouse, modList) {
        let mainFolderName = `0 ${describeList[1].data}$${Math.floor(Date.now() / 1000)} ${describeList[2].data}`;
        let mainFolderPath = path.join(fileHouse, mainFolderName);
        let clothingFolderPath = path.join(mainFolderPath, 'clothing');
        let previewFolderPath = path.join(mainFolderPath, 'preview');
        let modPathList = modList.map((mod, index) => {
            let modName = mod.filePath.split('\\').pop();
            if (index < 2) return path.join(clothingFolderPath, modName);
            if (index < 4) return path.join(mainFolderPath, modName);
            return path.join(previewFolderPath, modName);
        });

        return {
            modPathList,
            newFolderList: [mainFolderPath, clothingFolderPath, previewFolderPath],
            mainFolderPath,
            previewFolderPath
        };
    },
    // 各级文件转存
    modFileStore(pathList, fileList, targetPathList) {
        const isValidPath = (path) => !/[<>"|?*]/.test(path);

        try {
            console.log("pathList:", pathList); // 添加调试信息
            if (!pathList || !pathList.newFolderList) {
                throw new Error("pathList 或 pathList.newFolderList 未定义");
            }
            pathList.newFolderList.forEach(folder => {
                if (!isValidPath(folder)) throw new Error(`路径包含非法字符：${folder}`);
                fs.mkdirSync(folder, { recursive: true });
            });

            mainApi.writeDailyLog(`新建文件夹成功\n${pathList.newFolderList.join('\n')}`);
            this.fileStoreRun(fileList, targetPathList);
            ElMessage({ message: `${path.basename(pathList.mainFolderPath)}转存成功` });
        } catch (err) {
            ElMessage.error({ message: `文件夹创建失败：${err.message}` });
            mainApi.writeDailyLog(`文件夹创建失败：${err.message}-uploadApi.js`);
        }
    },
    // 统一执行文件转存
    fileStoreRun(sourcePathList, targetPathList) {
        sourcePathList.forEach(source => {
            if (source.filePath === "") return;
            targetPathList.forEach(target => {
                if (target.name === source.name) {
                    try {
                        fs.copyFileSync(source.filePath, target.filePath);
                        ElMessage({ message: `${source.name}转存成功` });
                    } catch (err) {
                        ElMessage.error({ message: `${source.name}转存失败:${err}` });
                        mainApi.writeDailyLog(`${source.name}转存失败:${err}\n源路径:${source.filePath}\n目标路径:${target.filePath}--upLoadApi.js`);
                        fs.rm(path.dirname(target.filePath), { recursive: true }, (err) => {
                            if (err) mainApi.writeDailyLog(`删除${path.dirname(target.filePath)}文件夹失败:${err}--upLoadApi.js`);
                            else mainApi.writeDailyLog(`删除${path.dirname(target.filePath)}文件夹成功--upLoadApi.js`);
                        });
                    }
                }
            });
        });
    },
    // 整合文件夹文件识别
    folderFileIdentify(fileList, dataList, matchType, callback) {
        // 结果
        let resultList = [];
        // 匹配
        if (!matchType) {
            // 单文件mod类型
            Object.values(fileList).forEach(file => {
                // 文件类型区分
                if (file.name.split(".")[1] === "iff") {
                    // console.log(`非图片：${file.name}`);
                    // 非图片
                    resultList.push({
                        name: dataList[0].name,
                        filePath: file.path
                    });
                } else {
                    // console.log(`图片：${file.name}`);
                    // 图片
                    resultList.push({
                        name: dataList[1].name,
                        filePath: file.path
                    });
                }
            });
        }
        // 面补匹配
        else if (matchType === "face") {
            // 字符标识列表
            let flagList = [];
            let arr = [dataList[0], dataList[1]];
            arr.forEach(data => {
                flagList.push(data.name.split("_")[1].split(".")[0]);
            });
            // 分类
            Object.values(fileList).forEach(file => {
                // 文件类型区分
                if (file.name.split(".")[1] === "iff") {
                    // 非图片
                    flagList.forEach(flag => {
                        if (file.name.indexOf(flag) != -1) {
                            // 文件名录入
                            resultList.push({
                                name: `_${flag}.iff`,
                                filePath: file.path
                            });
                        }
                    });
                } else {
                    // 图片
                    resultList.push({
                        name: dataList[2].name,
                        filePath: file.path
                    });
                }
            });
        }
        // 球衣匹配
        else if (matchType === "jersey") {
            // iff部分处理
            let iffList = [dataList[0], dataList[1], dataList[2], dataList[3]];
            // 字符标识列表
            let flagList = [];
            iffList.forEach(data => {
                flagList.push(data.name.split("_")[1].split(".")[0]);
            });
            console.log(flagList);
            // 分类
            Object.values(fileList).forEach(file => {
                // 文件类型区分
                if (file.name.split(".")[1] === "iff") {
                    // 非图片
                    flagList.forEach(flag => {
                        if (file.name.indexOf(flag) != -1) {
                            // _current.iff特殊处理
                            if (flag === "current" && file.name.indexOf("clothing_resource") != -1) return;
                            // 文件名录入
                            resultList.push({
                                name: `_${flag}.iff`,
                                filePath: file.path
                            });
                        }
                    });
                } else {
                    // 图片
                    resultList.push({
                        name: dataList[4].name,
                        filePath: file.path
                    });
                }
            });
        }

        // 返回
        callback(resultList);
    },
    // 面补文件夹编号更新
    faceFolderNumChange(fromNum, toNum) {
        // 读取所有需要重命名的文件夹
        mainApi.readJson(ElMessage, (data) => {
            // 读取面补集路径
            let faceSetPath = path.join(data.fileHouse, "face", fromNum);
            console.log(faceSetPath);
            // 验证面补集路径
            if (!fs.existsSync(faceSetPath)) {
                ElMessage({ message: `未找到编号为${fromNum}的文件夹`, type: "error" });
                return;
            }
            // 读取面补文件夹列表
            let currentFaceList = [];
            try {
                currentFaceList = fs.readdirSync(faceSetPath);
            } catch (err) {
                ElMessage({ message: `遍历${faceSetPath}文件夹失败：${err}`, type: "error" });
                mainApi.writeDailyLog(`遍历${faceSetPath}文件夹失败：${err}` + "--upLoadApi.js");
            }
            console.log(currentFaceList);
            // 批量重命名面补文件夹
            currentFaceList.forEach(face => {
                // 检查 faceSetPath 和 face 是否为字符串
                if (typeof faceSetPath !== 'string' || typeof face !== 'string') {
                    ElMessage({ message: `无效的路径参数: faceSetPath 或 face 不是字符串`, type: "error" });
                    mainApi.writeDailyLog(`无效的路径参数: faceSetPath 或 face 不是字符串` + "--upLoadApi.js");
                    return;
                }

                // 旧文件夹路径
                let oldPath;
                try {
                    oldPath = path.join(faceSetPath, face);
                } catch (err) {
                    ElMessage({ message: `生成旧文件夹路径时出错: ${err.message}`, type: "error" });
                    mainApi.writeDailyLog(`生成旧文件夹路径时出错: ${err.message}` + "--upLoadApi.js");
                    return;
                }

                // 检查 data.fileHouse, fromNum 和 toNum 是否为字符串
                if (typeof data.fileHouse !== 'string' || typeof fromNum !== 'string' || typeof toNum !== 'string') {
                    ElMessage({ message: `无效的路径参数: data.fileHouse, fromNum 或 toNum 不是字符串`, type: "error" });
                    mainApi.writeDailyLog(`无效的路径参数: data.fileHouse, fromNum 或 toNum 不是字符串` + "--upLoadApi.js");
                    return;
                }

                // 新文件夹路径
                let newPath;
                try {
                    newPath = path.join(data.fileHouse, "face", fromNum, toNum + face.slice(fromNum.length));
                } catch (err) {
                    ElMessage({ message: `生成新文件夹路径时出错: ${err.message}`, type: "error" });
                    mainApi.writeDailyLog(`生成新文件夹路径时出错: ${err.message}` + "--upLoadApi.js");
                    return;
                }

                // 执行重命名
                fs.rename(oldPath, newPath, (err) => {
                    // 失败
                    if (err) {
                        ElMessage({ message: `变更${oldPath}时失败,错误为:${err}`, type: "error" });
                        mainApi.writeDailyLog(`变更${oldPath}时失败,错误为:${err}` + "--upLoadApi.js");
                        return;
                    }
                    // 成功
                    ElMessage({ message: `变更${oldPath}成功` });
                    mainApi.writeDailyLog(`变更${oldPath}成功,已重命名为${newPath}` + "--upLoadApi.js");
                });
            });

            // 重命名面补集文件夹
            if (typeof data.fileHouse !== 'string' || typeof toNum !== 'string') {
                ElMessage({ message: `无效的路径参数: data.fileHouse 或 toNum 不是字符串`, type: "error" });
                mainApi.writeDailyLog(`无效的路径参数: data.fileHouse 或 toNum 不是字符串` + "--upLoadApi.js");
                return;
            }

            let newFaceSetPath;
            try {
                newFaceSetPath = path.join(data.fileHouse, "face", toNum);
            } catch (err) {
                ElMessage({ message: `生成新面补集文件夹路径时出错: ${err.message}`, type: "error" });
                mainApi.writeDailyLog(`生成新面补集文件夹路径时出错: ${err.message}` + "--upLoadApi.js");
                return;
            }

            fs.rename(faceSetPath, newFaceSetPath, (err) => {
                // 失败
                if (err) {
                    ElMessage({ message: `变更${faceSetPath}时失败,错误为:${err}`, type: "error" });
                    mainApi.writeDailyLog(`变更${faceSetPath}时失败,错误为:${err}` + "--upLoadApi.js");
                    return;
                }
                // 成功
                ElMessage({ message: `变更${faceSetPath}成功` });
                mainApi.writeDailyLog(`变更${faceSetPath}成功,已重命名为${newFaceSetPath}` + "--upLoadApi.js");
            });
        });
    }
}